package setting

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
	"likeadmin/admin/schemas/req"
	"likeadmin/admin/schemas/resp"
	"likeadmin/core/request"
	"likeadmin/core/response"
	"likeadmin/dao"
	"likeadmin/model"
)

type INoticeSettingService interface {
	List(c *gin.Context, page request.PageReq, listReq req.NoticeSettingListReq) (res response.PageResp, e error)
	Detail(c *gin.Context, id int32) (res resp.NoticeSettingResp, e error)
	Edit(c *gin.Context, editReq req.NoticeSettingEditReq) (e error)
}

// NewNoticeSettingService 初始化
func NewNoticeSettingService(db *gorm.DB, dao *dao.Query) INoticeSettingService {
	return &noticeSettingService{db: db, dao: dao}
}

// noticeSettingService 通知设置服务实现类
type noticeSettingService struct {
	db  *gorm.DB
	dao *dao.Query
}

// List 通知设置列表
func (srv noticeSettingService) List(c *gin.Context, page request.PageReq, listReq req.NoticeSettingListReq) (res response.PageResp, e error) {
	// 分页信息
	limit := page.PageSize
	offset := page.PageSize * (page.PageNo - 1)

	// 总数
	var count int64
	m := srv.dao.NoticeSetting
	q := m.WithContext(c)

	q = q.Where(m.Recipient.Eq(listReq.Recipient))

	count, err := q.Count()
	if e = response.CheckErr(err, "List Count err"); e != nil {
		return
	}

	notices, err := q.Limit(limit).Offset(offset).Find()
	if e = response.CheckErr(err, "List Find err"); e != nil {
		return
	}

	return response.PageResp{
		PageNo:   page.PageNo,
		PageSize: page.PageSize,
		Count:    count,
		Lists:    notices,
	}, nil
}

// Detail 通知设置详情
func (srv noticeSettingService) Detail(c *gin.Context, id int32) (res resp.NoticeSettingResp, e error) {
	m := srv.dao.NoticeSetting
	q := m.WithContext(c)

	first, err := q.Where(m.ID.Eq(id)).First()
	if e = response.CheckErrDBNotRecord(err, "数据不存在!"); e != nil {
		return
	}
	if e = response.CheckErr(err, "Detail First err"); e != nil {
		return
	}

	response.Copy(&res, first)
	return
}

// Edit 通知设置编辑
func (srv noticeSettingService) Edit(c *gin.Context, editReq req.NoticeSettingEditReq) (e error) {

	m := srv.dao.NoticeSetting
	q := m.WithContext(c)

	_, err := q.Where(m.ID.Eq(editReq.Id)).Select(m.ID).Take()
	// 校验
	if e = response.CheckErrDBNotRecord(err, "数据不存在!"); e != nil {
		return
	}
	if e = response.CheckErr(err, "Edit First err"); e != nil {
		return
	}

	SmsNoticeStr, _ := json.Marshal(editReq.Template.SmsNotice)
	if err != nil {
		return err
	}

	mod := &model.NoticeSetting{
		ID:        editReq.Id,
		SmsNotice: string(SmsNoticeStr),
	}
	// 更新
	_, err = q.Where(m.ID.Eq(editReq.Id)).Updates(mod)

	e = response.CheckErr(err, "Edit Updates err")
	return
}
